package com.zm.openapi.config;

import com.zm.openapi.bo.AppSecretBo;
import com.zm.openapi.constants.OpenApiConstants;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import reactor.core.publisher.Mono;

/**
 * @description: 配置
 * @module: com.zm.apigateway.config
 * @author: songxiongli
 * @date: 2020-03-13 23:30
 **/
@SpringBootConfiguration
public class GatewayWebConfig {

    /**
     * gateway里有调用servlet 模式的feignclient必须注入
     * 暂时不知道原因
     *
     * @return
     */
    @Bean
    public HttpMessageConverters httpMessageConverters() {
        HttpMessageConverters converters = new HttpMessageConverters();
        return converters;
    }

    @Bean
    public KeyResolver appIdKeyResolver() {
        return exchange -> Mono.just(OpenApiConstants.APP_ID + "_" + exchange.getRequest().getHeaders().getFirst(OpenApiConstants.APP_ID));
    }

    @Bean
    public RedisTemplate<String, Integer> redisTemplate(LettuceConnectionFactory connectionFactory) {
        //创建 redisTemplate 模版
        RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<>();

        //设置 value 的转化格式和 key 的转化格式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //关联 redisConnectionFactory
        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }

    @Bean
    public RedisTemplate<String, AppSecretBo> appSecretRedisTemplate(LettuceConnectionFactory connectionFactory) {
        //创建 redisTemplate 模版
        RedisTemplate<String, AppSecretBo> redisTemplate = new RedisTemplate<>();

        //设置 value 的转化格式和 key 的转化格式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //关联 redisConnectionFactory
        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }


}
